from fastapi.responses import JSONResponse
from fastapi import Request, FastAPI
import logging

from ..pojo.vo.Result import Result
from ..common.exception import FileNotSupportedException


def register_exception_handler(app: FastAPI):
    @app.exception_handler(404)
    async def notFoundHandler(request: Request, exc):
        logging.error(f"全局异常处理器捕获到异常: {type(exc).__name__}")
        return JSONResponse(
            status_code=200,
            content=Result.error("请求地址不存在").model_dump(),
        )

    @app.exception_handler(Exception)
    async def globalExceptionHandler(request: Request, exc):
        logging.error(f"全局异常处理器捕获到异常: {type(exc).__name__}")
        return JSONResponse(
            status_code=200,
            content=Result.error("服务器内部错误, 请联系管理员").model_dump(),
        )

    @app.exception_handler(FileNotSupportedException)
    async def file_not_supported_handler(
        request: Request, exc: FileNotSupportedException
    ):
        logging.error(
            f"""
            文件不支持异常:
            文件名: {exc.file_name}
            类型: {exc.file_type}
            时间: {exc.timestamp}
            详细信息: {exc.extra_info}
        """
        )

        message = "文件类型不支持"
        data = {
            "fileType": exc.file_type,
            "fileName": exc.file_name,
            "timestamp": exc.timestamp,
            "extraInfo": exc.extra_info,
        }

        return JSONResponse(
            status_code=200,
            content=Result.error(message, data).model_dump(exclude_none=True),
        )

    logging.info("全局异常处理器注册成功!!!...")
